{% extends 'base.html' %}
{% load static %}

{% block title %}创建活动 - 本地有约{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">创建新活动</h4>
                </div>
                <div class="card-body">
                    <!-- 成功消息 -->
                    <div class="alert alert-success" id="successMessage" style="display: none;">
                        <i class="fas fa-check-circle"></i>
                        <strong id="successText"></strong>
                    </div>

                    <form id="createActivityForm" method="POST" enctype="multipart/form-data">
                        {% csrf_token %}

                        <!-- 活动标题 -->
                        <div class="mb-3">
                            <label for="activityTitle" class="form-label">活动标题 *</label>
                            <input type="text" class="form-control" name="title" id="activityTitle"
                                   placeholder="例如：周末羽毛球友谊赛" required maxlength="200">
                            <div class="form-text">简洁明了的标题能吸引更多参与者</div>
                        </div>

                        <!-- 活动分类 -->
                        <div class="mb-3">
                            <label class="form-label">活动分类 *</label>
                            <div class="row">
                                {% for category in categories %}
                                <div class="col-md-3 mb-2">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="category"
                                               id="category{{ category.id }}" value="{{ category.id }}"
                                               {% if forloop.first %}checked{% endif %}>
                                        <label class="form-check-label" for="category{{ category.id }}">
                                            <i class="{{ category.icon|default:'fas fa-star' }}"></i>
                                            {{ category.name }}
                                        </label>
                                    </div>
                                </div>
                                {% empty %}
                                <div class="col-12">
                                    <div class="alert alert-warning">暂无活动分类</div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>

                        <!-- 活动时间 -->
                        <div class="mb-3">
                            <label class="form-label">活动时间 *</label>
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">开始时间</label>
                                    <input type="datetime-local" class="form-control" name="start_time" id="startTime" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">结束时间</label>
                                    <input type="datetime-local" class="form-control" name="end_time" id="endTime" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">报名截止时间</label>
                                    <input type="datetime-local" class="form-control" name="registration_deadline" id="registrationDeadline" required>
                                </div>
                            </div>
                        </div>

                        <!-- 活动地点 -->
                        <div class="mb-3">
                            <label class="form-label">活动地点 *</label>

                            <!-- 地址搜索 -->
                            <div class="mb-2">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="locationSearch" placeholder="搜索地址...">
                                    <button type="button" class="btn btn-outline-secondary" id="searchLocationBtn">
                                        <i class="fas fa-search"></i> 搜索
                                    </button>
                                </div>
                            </div>

                            <!-- 详细地址 -->
                            <div class="mb-2">
                                <input type="text" class="form-control" name="location" id="location" placeholder="输入详细地址" required>
                            </div>

                            <!-- 地图容器 -->
                            <div class="mb-2 border rounded" style="height: 300px; position: relative;">
                                <div id="mapContainer" style="height: 100%; width: 100%;">
                                    <div class="d-flex justify-content-center align-items-center h-100">
                                        <div class="text-center">
                                            <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
                                            <p>地图加载中...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 坐标显示 -->
                            <div class="row mb-2">
                                <div class="col-md-6">
                                    <label class="form-label">纬度</label>
                                    <input type="number" step="any" class="form-control" name="latitude" id="latitude" placeholder="纬度" required readonly>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">经度</label>
                                    <input type="number" step="any" class="form-control" name="longitude" id="longitude" placeholder="经度" required readonly>
                                </div>
                            </div>

                            <!-- 位置操作按钮 -->
                            <div class="mb-2">
                                <button type="button" class="btn btn-outline-primary btn-sm" id="getCurrentLocationBtn">
                                    <i class="fas fa-location-arrow"></i> 获取当前位置
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" id="clearLocationBtn">
                                    <i class="fas fa-times"></i> 清除位置
                                </button>
                            </div>

                            <div class="form-text">
                                <i class="fas fa-info-circle"></i>
                                点击地图选择位置，或搜索地址自动定位
                            </div>
                        </div>

                        <!-- 人数限制 -->
                        <div class="mb-3">
                            <label for="maxParticipants" class="form-label">最多参与人数 *</label>
                            <input type="range" class="form-range" name="max_participants" id="maxParticipants"
                                   min="2" max="100" value="10" oninput="updateParticipantCount(this.value)">
                            <div class="d-flex justify-content-between">
                                <span>2人</span>
                                <span id="participantCount">10人</span>
                                <span>100人</span>
                            </div>
                        </div>

                        <!-- 费用设置 -->
                        <div class="mb-3">
                            <label class="form-label">费用设置 *</label>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="is_free" id="freeActivity" value="true" checked>
                                        <label class="form-check-label" for="freeActivity">
                                            <i class="fas fa-gift"></i> 免费活动
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="is_free" id="paidActivity" value="false">
                                        <label class="form-check-label" for="paidActivity">
                                            <i class="fas fa-coins"></i> 收费活动
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div id="feeAmountGroup" style="display: none;">
                                        <label for="feeAmount" class="form-label">费用金额</label>
                                        <div class="input-group">
                                            <span class="input-group-text">¥</span>
                                            <input type="number" class="form-control" name="fee" id="feeAmount"
                                                   placeholder="0.00" min="0" step="0.01" value="0">
                                            <span class="input-group-text">元/人</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 活动描述 -->
                        <div class="mb-3">
                            <label for="activityDescription" class="form-label">活动描述 *</label>
                            <textarea class="form-control" name="description" id="activityDescription"
                                      rows="5" placeholder="详细描述您的活动内容、流程、注意事项等..."
                                      required maxlength="1000"></textarea>
                            <div class="form-text">
                                <span id="charCount">剩余 1000 字符</span>
                            </div>
                        </div>

                        <!-- 上传图片 -->
                        <div class="mb-3">
                            <label class="form-label">活动图片</label>
                            <input type="file" class="form-control" name="images" id="imageInput"
                                   accept="image/*" multiple>
                            <div class="form-text">支持 JPG、PNG 格式，最大 5MB</div>

                            <div id="imagePreview" class="mt-2" style="display: none;">
                                <div class="row" id="previewContainer">
                                    <!-- 图片预览将在这里显示 -->
                                </div>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary" onclick="window.history.back()">
                                <i class="fas fa-times"></i> 取消
                            </button>
                            <div>
                                <!-- 存草稿按钮 -->
                                <button type="button" class="btn btn-outline-secondary me-2" id="saveDraftBtn">
                                    <div class="spinner-border spinner-border-sm" id="draftLoadingSpinner" style="display: none;"></div>
                                    <i class="fas fa-save" id="draftIcon"></i>
                                    <span id="draftText">存草稿</span>
                                </button>

                                <!-- 发布活动按钮 -->
                                <button type="submit" class="btn btn-primary" id="submitBtn">
                                    <div class="spinner-border spinner-border-sm" id="loadingSpinner" style="display: none;"></div>
                                    <i class="fas fa-rocket" id="submitIcon"></i>
                                    <span id="submitText">发布活动</span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<!-- 引入百度地图API -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=rUiyl00fneDC8rieZJagiXxwyDl7ZYje"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('活动创建页面初始化开始...');

    // 初始化所有功能
    initMapFunctions();
    initFormInteractions();
    initImageUpload();
    initFormValidation();
    initDraftFunction();

    console.log('活动创建页面初始化完成');
});

// 表单验证函数
function validateForm() {
    const title = document.getElementById('activityTitle').value.trim();
    const description = document.getElementById('activityDescription').value.trim();
    const location = document.getElementById('location').value.trim();
    const latitude = document.getElementById('latitude').value;
    const longitude = document.getElementById('longitude').value;
    const startTime = document.getElementById('startTime').value;
    const endTime = document.getElementById('endTime').value;
    const registrationDeadline = document.getElementById('registrationDeadline').value;

    // 验证必填字段
    const requiredFields = [
        { field: title, name: '活动标题', element: 'activityTitle' },
        { field: description, name: '活动描述', element: 'activityDescription' },
        { field: location, name: '活动地点', element: 'location' },
        { field: latitude, name: '纬度坐标', element: null },
        { field: longitude, name: '经度坐标', element: null },
        { field: startTime, name: '开始时间', element: 'startTime' },
        { field: endTime, name: '结束时间', element: 'endTime' },
        { field: registrationDeadline, name: '报名截止时间', element: 'registrationDeadline' }
    ];

    for (let field of requiredFields) {
        if (!field.field) {
            showAlert(`请填写${field.name}`, 'warning');
            if (field.element) {
                document.getElementById(field.element).focus();
            }
            return false;
        }
    }

    // 验证时间逻辑
    const start = new Date(startTime);
    const end = new Date(endTime);
    const deadline = new Date(registrationDeadline);
    const now = new Date();

    if (start <= now) {
        showAlert('开始时间必须晚于当前时间', 'warning');
        return false;
    }

    if (end <= start) {
        showAlert('结束时间必须晚于开始时间', 'warning');
        return false;
    }

    if (deadline >= start) {
        showAlert('报名截止时间必须早于活动开始时间', 'warning');
        return false;
    }

    if (deadline <= now) {
        showAlert('报名截止时间必须晚于当前时间', 'warning');
        return false;
    }

    // 验证费用
    const paidActivity = document.getElementById('paidActivity');
    const feeAmount = document.getElementById('feeAmount');
    if (paidActivity.checked) {
        const fee = parseFloat(feeAmount.value);
        if (isNaN(fee) || fee <= 0) {
            showAlert('请填写正确的活动费用', 'warning');
            feeAmount.focus();
            return false;
        }
    }

    // 验证图片
    const imageInput = document.getElementById('imageInput');
    if (imageInput.files.length > 0) {
        for (let file of imageInput.files) {
            // 验证文件大小
            if (file.size > 5 * 1024 * 1024) {
                showAlert(`图片 "${file.name}" 大小超过5MB限制`, 'warning');
                return false;
            }

            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                showAlert(`文件 "${file.name}" 不是图片格式`, 'warning');
                return false;
            }

            // 验证文件扩展名
            const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            const fileExtension = file.name.split('.').pop().toLowerCase();
            if (!validExtensions.includes(fileExtension)) {
                showAlert(`图片 "${file.name}" 格式不支持，请使用 JPG、PNG、GIF 或 WebP 格式`, 'warning');
                return false;
            }
        }
    }

    console.log('表单验证通过');
    return true;
}

// 草稿验证函数
function validateDraft() {
    const title = document.getElementById('activityTitle').value.trim();

    if (!title) {
        showAlert('请输入活动标题', 'warning');
        return false;
    }

    return true;
}

// 地图功能
function initMapFunctions() {
    let map = null;
    let marker = null;
    let geocoder = null;

    // 初始化地图
    function initMap() {
        const mapContainer = document.getElementById('mapContainer');

        try {
            map = new BMap.Map("mapContainer");
            geocoder = new BMap.Geocoder();

            // 默认定位到北京
            const defaultPoint = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(defaultPoint, 12);
            map.enableScrollWheelZoom(true);

            // 添加地图控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());

            // 地图点击事件
            map.addEventListener("click", function(e) {
                setMarkerPosition(e.point);
                reverseGeocode(e.point);
            });

            // 隐藏加载提示
            const loadingElement = mapContainer.querySelector('.d-flex');
            if (loadingElement) {
                loadingElement.style.display = 'none';
            }

            console.log('百度地图初始化成功');
        } catch (error) {
            console.error('百度地图初始化失败:', error);
            const loadingElement = mapContainer.querySelector('.d-flex');
            if (loadingElement) {
                loadingElement.innerHTML = '<div class="text-center text-danger"><i class="fas fa-exclamation-triangle fa-2x mb-2"></i><p>地图加载失败，请刷新页面重试</p></div>';
            }
        }
    }

    function setMarkerPosition(point) {
        if (marker) {
            map.removeOverlay(marker);
        }

        marker = new BMap.Marker(point);
        map.addOverlay(marker);

        document.getElementById('latitude').value = point.lat.toFixed(6);
        document.getElementById('longitude').value = point.lng.toFixed(6);
        map.panTo(point);
    }

    function reverseGeocode(point) {
        geocoder.getLocation(point, function(result) {
            if (result) {
                document.getElementById('location').value = result.address;
            }
        });
    }

    function searchLocation(address) {
        if (!address) {
            showAlert('请输入要搜索的地址', 'warning');
            return;
        }

        geocoder.getPoint(address, function(point) {
            if (point) {
                setMarkerPosition(point);
                map.centerAndZoom(point, 16);
                reverseGeocode(point);
                showAlert('位置搜索成功！', 'success');
            } else {
                showAlert('未找到相关地址', 'warning');
            }
        });
    }

    function getCurrentLocation() {
        if (navigator.geolocation) {
            showAlert('正在获取位置...', 'info');

            navigator.geolocation.getCurrentPosition(
                function(position) {
                    const point = new BMap.Point(position.coords.longitude, position.coords.latitude);
                    setMarkerPosition(point);
                    map.centerAndZoom(point, 16);
                    reverseGeocode(point);
                    showAlert('位置获取成功！', 'success');
                },
                function(error) {
                    let message = '无法获取位置';
                    switch(error.code) {
                        case error.PERMISSION_DENIED: message = '位置访问被拒绝'; break;
                        case error.POSITION_UNAVAILABLE: message = '位置信息不可用'; break;
                        case error.TIMEOUT: message = '获取位置超时'; break;
                    }
                    showAlert(message, 'warning');
                }
            );
        } else {
            showAlert('浏览器不支持地理位置服务', 'warning');
        }
    }

    function clearLocation() {
        if (marker) {
            map.removeOverlay(marker);
            marker = null;
        }
        document.getElementById('latitude').value = '';
        document.getElementById('longitude').value = '';
        document.getElementById('location').value = '';
        document.getElementById('locationSearch').value = '';
    }

    // 绑定事件
    document.getElementById('searchLocationBtn').addEventListener('click', function() {
        searchLocation(document.getElementById('locationSearch').value);
    });

    document.getElementById('locationSearch').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            searchLocation(this.value);
        }
    });

    document.getElementById('getCurrentLocationBtn').addEventListener('click', getCurrentLocation);
    document.getElementById('clearLocationBtn').addEventListener('click', clearLocation);

    // 延迟初始化地图
    setTimeout(initMap, 500);
}

// 表单交互
function initFormInteractions() {
    // 人数滑块同步
    const participantsSlider = document.getElementById('maxParticipants');

    function updateParticipantCount(value) {
        document.getElementById('participantCount').textContent = value + '人';
    }

    participantsSlider.addEventListener('input', function() {
        updateParticipantCount(this.value);
    });

    // 费用设置切换
    const freeActivity = document.getElementById('freeActivity');
    const paidActivity = document.getElementById('paidActivity');
    const feeAmountGroup = document.getElementById('feeAmountGroup');

    function toggleFeeAmount() {
        if (paidActivity.checked) {
            feeAmountGroup.style.display = 'block';
            document.getElementById('feeAmount').required = true;
        } else {
            feeAmountGroup.style.display = 'none';
            document.getElementById('feeAmount').required = false;
            document.getElementById('feeAmount').value = '0';
        }
    }

    freeActivity.addEventListener('change', toggleFeeAmount);
    paidActivity.addEventListener('change', toggleFeeAmount);
    toggleFeeAmount(); // 初始化

    // 时间设置
    const startTime = document.getElementById('startTime');
    const endTime = document.getElementById('endTime');
    const registrationDeadline = document.getElementById('registrationDeadline');

    // 设置最小时间为当前时间
    const now = new Date();
    const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
        .toISOString()
        .slice(0, 16);

    startTime.min = localDateTime;
    endTime.min = localDateTime;
    registrationDeadline.min = localDateTime;

    startTime.addEventListener('change', function() {
        endTime.min = this.value;
        registrationDeadline.max = this.value;

        // 自动设置默认时间
        if (!endTime.value) {
            const startDate = new Date(this.value);
            startDate.setHours(startDate.getHours() + 2);
            endTime.value = startDate.toISOString().slice(0, 16);
        }

        if (!registrationDeadline.value) {
            const startDate = new Date(this.value);
            startDate.setHours(startDate.getHours() - 1);
            registrationDeadline.value = startDate.toISOString().slice(0, 16);
        }
    });

    // 描述字符计数
    const descTextarea = document.getElementById('activityDescription');
    descTextarea.addEventListener('input', function() {
        const length = this.value.length;
        const remaining = 1000 - length;
        const charCount = document.getElementById('charCount');

        charCount.textContent = `剩余 ${remaining} 字符`;

        if (remaining < 0) {
            charCount.style.color = '#dc3545';
        } else if (remaining < 100) {
            charCount.style.color = '#ffc107';
        } else {
            charCount.style.color = '#6c757d';
        }
    });
}

// 图片上传
function initImageUpload() {
    const imageInput = document.getElementById('imageInput');
    const previewContainer = document.getElementById('previewContainer');
    const imagePreview = document.getElementById('imagePreview');

    let uploadedImages = [];

    imageInput.addEventListener('change', (e) => {
        handleImageFiles(e.target.files);
    });

    function handleImageFiles(files) {
        for (let file of files) {
            if (file.type.startsWith('image/') && file.size <= 5 * 1024 * 1024) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    uploadedImages.push({
                        file: file,
                        dataUrl: e.target.result
                    });
                    updateImagePreview();
                };
                reader.readAsDataURL(file);
            } else {
                showAlert('请上传小于5MB的图片文件', 'error');
            }
        }
    }

    function updateImagePreview() {
        if (uploadedImages.length > 0) {
            imagePreview.style.display = 'block';
            previewContainer.innerHTML = '';

            uploadedImages.forEach((imageData, index) => {
                const colDiv = document.createElement('div');
                colDiv.className = 'col-md-3 mb-2';
                colDiv.innerHTML = `
                    <div class="card">
                        <img src="${imageData.dataUrl}" class="card-img-top" alt="预览图片" style="height: 100px; object-fit: cover;">
                        <div class="card-body p-2">
                            <button type="button" class="btn btn-danger btn-sm w-100" onclick="removeImage(${index})">
                                <i class="fas fa-times"></i> 删除
                            </button>
                        </div>
                    </div>
                `;
                previewContainer.appendChild(colDiv);
            });
        } else {
            imagePreview.style.display = 'none';
        }
    }

    window.removeImage = function(index) {
        uploadedImages.splice(index, 1);
        updateImagePreview();
    };
}

// 表单验证和提交
function initFormValidation() {
    const form = document.getElementById('createActivityForm');
    const submitBtn = document.getElementById('submitBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const submitIcon = document.getElementById('submitIcon');
    const submitText = document.getElementById('submitText');
    const successMessage = document.getElementById('successMessage');
    const successText = document.getElementById('successText');

    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        // 显示加载状态
        submitBtn.disabled = true;
        loadingSpinner.style.display = 'inline-block';
        submitIcon.style.display = 'none';
        submitText.textContent = '提交中...';  // 修改文本

        try {
            const formData = new FormData(form);
            // 注意：这里不添加 is_draft 参数，表示是正式提交审核

            const response = await fetch('', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                }
            });

            const data = await response.json();

            if (data.success) {
                successText.textContent = data.message;
                successMessage.style.display = 'block';
                showAlert(data.message, 'success');

                // 重定向到首页
                setTimeout(() => {
                    window.location.href = data.redirect_url;
                }, 2000);  // 稍微延长显示时间
            } else {
                throw new Error(data.message);
            }

        } catch (error) {
            console.error('Error:', error);
            showAlert('活动提交失败：' + error.message, 'error');

            // 恢复按钮状态
            submitBtn.disabled = false;
            loadingSpinner.style.display = 'none';
            submitIcon.style.display = 'inline-block';
            submitText.textContent = '提交审核';  // 恢复文本
        }
    });

    // ... 其他代码保持不变 ...
}


// 草稿功能
function initDraftFunction() {
    const draftBtn = document.getElementById('saveDraftBtn');
    const draftLoadingSpinner = document.getElementById('draftLoadingSpinner');
    const draftIcon = document.getElementById('draftIcon');
    const draftText = document.getElementById('draftText');

    draftBtn.addEventListener('click', async function(e) {
        e.preventDefault();

        if (!validateDraft()) {
            return;
        }

        // 显示加载状态
        draftBtn.disabled = true;
        draftLoadingSpinner.style.display = 'inline-block';
        draftIcon.style.display = 'none';
        draftText.textContent = '保存中...';

        try {
            const formData = new FormData(document.getElementById('createActivityForm'));
            formData.append('is_draft', 'true'); // 添加草稿标识

            const response = await fetch('', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                }
            });

            const data = await response.json();

            if (data.success) {
                showAlert(data.message, 'success');

                // 重定向到首页
                setTimeout(() => {
                    window.location.href = data.redirect_url;
                }, 1500);
            } else {
                throw new Error(data.message);
            }

        } catch (error) {
            console.error('Error:', error);
            showAlert('保存草稿失败：' + error.message, 'error');

            // 恢复按钮状态
            draftBtn.disabled = false;
            draftLoadingSpinner.style.display = 'none';
            draftIcon.style.display = 'inline-block';
            draftText.textContent = '存草稿';
        }
    });
}

// 工具函数 - 显示提示
function showAlert(message, type = 'info') {
    // 移除现有提示
    const existingAlert = document.querySelector('.custom-alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    }[type] || 'alert-info';

    const alert = document.createElement('div');
    alert.className = `alert ${alertClass} alert-dismissible fade show custom-alert`;
    alert.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alert);

    // 自动移除
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, 5000);
}

// 全局函数 - 更新参与者计数（用于HTML中的oninput）
function updateParticipantCount(value) {
    document.getElementById('participantCount').textContent = value + '人';
}
 // 检查是否有草稿数据需要预填充
    {% if draft %}
    const draftData = {
        id: {{ draft.id }},
        title: "{{ draft.title|default:''|escapejs }}",
        category: "{{ draft.category.id|default:'' }}",
        start_time: "{{ draft.start_time|date:'Y-m-d\\TH:i'|default:'' }}",
        end_time: "{{ draft.end_time|date:'Y-m-d\\TH:i'|default:'' }}",
        registration_deadline: "{{ draft.registration_deadline|date:'Y-m-d\\TH:i'|default:'' }}",
        location: "{{ draft.location|default:''|escapejs }}",
        latitude: {{ draft.latitude|default:0 }},
        longitude: {{ draft.longitude|default:0 }},
        max_participants: {{ draft.max_participants|default:10 }},
        is_free: {{ draft.is_free|yesno:"true,false" }},
        fee: {{ draft.fee|default:0 }},
        description: `{{ draft.description|default:''|escapejs }}`
    };

    console.log('加载草稿数据:', draftData);

    // 预填充表单数据到 Vue 实例或直接设置表单值
    if (typeof app !== 'undefined') {
        // 如果使用 Vue.js
        app.formData = { ...app.formData, ...draftData };
    } else {
        // 直接设置表单值
        setTimeout(() => {
            if (draftData.title) document.querySelector('[name="title"]').value = draftData.title;
            if (draftData.category) document.querySelector('[name="category"]').value = draftData.category;
            if (draftData.start_time) document.querySelector('[name="start_time"]').value = draftData.start_time;
            if (draftData.end_time) document.querySelector('[name="end_time"]').value = draftData.end_time;
            if (draftData.registration_deadline) document.querySelector('[name="registration_deadline"]').value = draftData.registration_deadline;
            if (draftData.location) document.querySelector('[name="location"]').value = draftData.location;
            if (draftData.latitude) document.querySelector('[name="latitude"]').value = draftData.latitude;
            if (draftData.longitude) document.querySelector('[name="longitude"]').value = draftData.longitude;
            if (draftData.max_participants) document.querySelector('[name="max_participants"]').value = draftData.max_participants;
            if (draftData.is_free !== undefined) document.querySelector('[name="is_free"]').checked = draftData.is_free;
            if (draftData.fee) document.querySelector('[name="fee"]').value = draftData.fee;
            if (draftData.description) document.querySelector('[name="description"]').value = draftData.description;

            // 添加隐藏字段标识正在编辑草稿
            const draftIdInput = document.createElement('input');
            draftIdInput.type = 'hidden';
            draftIdInput.name = 'draft_id';
            draftIdInput.value = draftData.id;
            document.querySelector('form').appendChild(draftIdInput);
        }, 100);
    }
    {% endif %}
</script>
{% endblock %}